/************************************************
 * Author       :   XXY
 * Blog         :   https://www.cnblogs.com/jzyl
 * Gitee        :   https://gitee.com/xiaobaichong
 * Email        :   1047185209@QQ.com
 * FileName     :   CsvHelper.cs
 * CreateData   :   2023/5/31 22:04:17
 * UnityVersion :   2021.3.20f1c1
 * Description  :   基于正则解析Csv
************************************************/

using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Main
{
    /// <summary>
    /// Csv 解析类
    /// </summary>
    public class CsvHelper
    {
        //// <summary>
        /// 字符串是否包含奇数个引号
        /// </summary>
        /// <param name="str">相关字符串</param>
        /// <returns></returns>
        private static bool _isOddDoubleQuota(string str)
        {
            return _getDoubleQuotaCount(str) % 2 == 1;
        }
        private static int _getDoubleQuotaCount(string str)
        {
            string[] strArray = str.Split('"');
            int doubleQuotaCount = strArray.Length - 1;
            doubleQuotaCount = doubleQuotaCount < 0 ? 0 : doubleQuotaCount;
            return doubleQuotaCount;
        }

        /// <summary>
        /// 从字符串解析 Csv
        /// </summary>
        /// <param name="csvInfo"></param>
        /// <returns></returns>
        public static Dictionary<int, List<string>> AnalysisCsvByStr(string csvInfo)
        {
            Dictionary<int, List<string>> csvInfoDic = new Dictionary<int, List<string>>();
            Regex regex = new Regex(@"\r\n");
            string[] infoLines = regex.Split(csvInfo);
            int Rows = 0;
            for (int i = 0; i < infoLines.Length; i++)
            {
                if (string.IsNullOrEmpty(infoLines[i]))
                {
                    continue;
                }
                string[] lineInfoArray = infoLines[i].Split(',');
                List<string> rowItemList = new List<string>();
                string strTemp = string.Empty;
                for (int j = 0; j < lineInfoArray.Length; j++)
                {
                    strTemp += lineInfoArray[j];
                    if (_isOddDoubleQuota(strTemp))
                    {
                        if (j != lineInfoArray.Length - 1)
                        {
                            strTemp += ",";
                        }
                    }
                    else
                    {
                        if (strTemp.StartsWith("\"") && strTemp.EndsWith("\""))
                        {
                            strTemp = strTemp.Substring(1, strTemp.Length - 2);
                        }
                        rowItemList.Add(strTemp);
                        strTemp = string.Empty;
                    }
                }
                csvInfoDic.Add(Rows++, rowItemList);
            }

            return csvInfoDic;
        }

        /// <summary>
        /// 从文件解析Csv
        /// </summary>
        /// <param name="csvPath"></param>
        /// <returns></returns>
        public static Dictionary<int, List<string>> AnalysisCsvByFile(string csvPath)
        {
            if (File.Exists(csvPath))
            {
                string csvInfo = File.ReadAllText(csvPath, Encoding.UTF8);
                return AnalysisCsvByStr(csvInfo);
            }
            else
            {
                throw new FileNotFoundException("未找到文件：" + csvPath);
            }
        }
        /// <summary>
        /// 将集合转化为CSV字符串
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string ConvertToCSV(Dictionary<int, List<string>> data)
        {
            StringBuilder csvStr = new StringBuilder();
            // [\n\.",]
            string pattern = $"[\\n\\.\",]";
            foreach (var entry in data.Values)
            {
                for (int i = 0; i < entry.Count; i++)
                {
                    if (Regex.IsMatch(entry[i], pattern))
                    {
                        csvStr.Append("\"" + entry[i] + "\"");
                    }
                    else
                    {
                        csvStr.Append(entry[i]);
                    }
                    if (i < entry.Count - 1)
                    {
                        csvStr.Append(",");
                    }
                }
                csvStr.Append("\r\n");
            }

            return csvStr.ToString();
        }
    }
}
